package com.pay.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pay.common.utils.MD5Utils;
import com.pay.common.utils.Result;
import com.pay.user.pojo.LoginDTO;
import com.pay.user.pojo.TUser;
import com.pay.user.service.TUserService;
import com.pay.user.mapper.TUserMapper;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
* @author 28242
* @description 针对表【t_user】的数据库操作Service实现
* @createDate 2025-08-08 12:01:45
*/
@Service
public class TUserServiceImpl extends ServiceImpl<TUserMapper, TUser>
    implements TUserService{

    @Autowired
    private TUserMapper tUserMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public Result login(LoginDTO loginVo) {
        TUser tUser = tUserMapper.selectOne(
                new QueryWrapper<TUser>().lambda().eq(TUser::getUsername, loginVo.getUsername())
        );
        if (tUser==null){
            return Result.error().setMsg("该用户不存在");
        }
        String password = MD5Utils.encrypt(loginVo.getPassword());
        System.out.println(password);

        if (!tUser.getPassword().equals(password)){
            return Result.error().setMsg("密码错误");
        }

        String token = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, "123456")
                .claim("userId", tUser.getId())
                .claim("userName", tUser.getUsername())
                .compact();
        String rediskey="token-"+tUser.getId();
        System.out.println(rediskey);

        redisTemplate.opsForValue().set(rediskey,token,15, TimeUnit.MINUTES);

        tUser.setToken(token);
        System.out.println(token);

        return Result.ok().setData(tUser);
    }
}




